package com.leetcode;

import java.util.*;

/**
 * 819. 最常见的单词
 * 双指针截取单词
 *
 * @author fy
 * @date 2022-04-17 13:38
 */
public class Solution819_2 {

    public String mostCommonWord(String paragraph, String[] banned) {
        String ans = "";
        int max = 0;
        int n = paragraph.length();
        paragraph = paragraph.toLowerCase();
        Set<String> set = new HashSet<>(Arrays.asList(banned));
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < n; ) {
            while (i < n && !Character.isLetter(paragraph.charAt(i))) {
                i++;
            }
            // 用于跳过空格
            int j = i + 1;
            while (j < n && Character.isLetter(paragraph.charAt(j))) {
                j++;
            }
            if (i < n && j <= n) {
                String str = paragraph.substring(i, j);
                if (!set.contains(str)) {
                    int cnt = map.getOrDefault(str, 0) + 1;
                    if (cnt > max) {
                        max = cnt;
                        ans = str;
                    }
                    map.put(str, cnt);
                }
            }
            i = j + 1;
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(Character.isLetter(' '));
        String paragraph = "Bob hit a ball ,the hit BALL flew far after it was hit .";
        String[] banned = new String[]{"hit"};

        String res = new Solution819_2().mostCommonWord(paragraph, banned);
        System.out.println(res);
    }

}
